package sample.web.filter;

import org.apache.commons.lang3.ArrayUtils;
import sample.web.model.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by zhaopeng on 2/29/16.
 */
public class LoginFilter implements Filter{
    private final static String[] static_ext = {"woff2", "woff", "ttf", "js", "css", "jpg", "png", "gif", "html", "ico", "vm", "swf"};
    private final static String[] whiteList = {"/user/login", "/user/regin"};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        String str=requestURI.substring(requestURI.lastIndexOf(".")+1,requestURI.length());
        System.out.println(str);
        if (ArrayUtils.contains(whiteList, requestURI) || ArrayUtils.contains(static_ext, str)) {
            filterChain.doFilter(request,response);
            return;
        }
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            System.out.println("user is null");
            response.sendRedirect("/user/login");
            return;
        } else {
            System.out.println(user.getUsername());
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }


}
